package org.goodsmanager.controller;

import org.goodsmanager.entity.User;
import org.goodsmanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 密码重置控制器（仅用于开发环境）
 */
@Controller
@RequestMapping("/reset")
public class PasswordResetController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    /**
     * 重置管理员密码
     */
    @GetMapping("/admin-password")
    @ResponseBody
    public Map<String, Object> resetAdminPassword(@RequestParam(required = false, defaultValue = "admin123") String newPassword) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取admin用户
            User adminUser = userService.getUserByUsername("admin");
            if (adminUser == null) {
                result.put("success", false);
                result.put("message", "Admin user not found");
                return result;
            }
            
            // 加密新密码
            String hashedPassword = passwordEncoder.encode(newPassword);
            
            // 更新密码
            adminUser.setPassword(hashedPassword);
            boolean updateResult = userService.updateUser(adminUser);
            
            if (updateResult) {
                result.put("success", true);
                result.put("message", "Admin password reset successfully");
                result.put("newPassword", newPassword);
                result.put("hashedPassword", hashedPassword);
            } else {
                result.put("success", false);
                result.put("message", "Failed to update admin password");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Error: " + e.getMessage());
        }
        
        return result;
    }
}